/*!
	@file		 	(framework)Server.js
	@abstract	 	Classes for the server execution
	@discussion	 	Includes the server compilator
	@author 		Created by Robin Ricard on 17/08/09.
	@licence 		This Document is under LGPL License, please read this document : http://www.gnu.org/licenses/lgpl-3.0-standalone.html
*/

/*!
	@class			GlueServerCompilator
	@abstract		Provides methods for analyse the page and superpose the layers 
*/
/*!
	@constructor
	@discussion	 	He is empty
*/
function GlueServerCompilator() {
	// (empty) //
}

/*!
	@method			compile
	@abstract		Read the target document and modify DOM to add the layers
	@property		target: the destination of the compilation (for example : document)
*/
GlueServerCompilator.prototype.compile = function(target) {
	var emplacements = getElementsByClass('glue:emplacement',target);
	for(var ei = 0;ei < emplacements.length;ei ++) {
		var layerLink = emplacements[ei].getAttribute('id');
		var splittedLink = layerLink.split('/');
		var pageToLoad = GlueUtils.GETParameter(splittedLink[0]);
		var zoneToLoad = splittedLink[1];
		
		if (new RegExp('\.\.\/').test(pageToLoad)) pageToLoad = layerDirPath+this.errorLayer;
		
		if(!pageToLoad)
			pageToLoad = this.defaultLayer;
		
		var layerDirPath = this.layerDir+'/'+splittedLink[0]+'/';
		var layerPath = layerDirPath+pageToLoad;
		if(!Jaxer.File.exists(layerPath))
			layerPath = layerDirPath+this.errorLayer;
		
		var fileContents = Jaxer.File.read(layerPath);
		var loadedXML = fileContents.toDOM();
		var nodesArray = loadedXML.childNodes;
		
		for(var xi = 0;xi < nodesArray.length;xi ++) {
			if(nodesArray[xi].attributes) {
				if(nodesArray[xi].attributes['id'].value == zoneToLoad){
					var newDom = nodesArray[xi];
					this.compile(newDom);
					emplacements[ei].innerHTML = newDom.innerHTML;
					break;
				}
			}
		}
	}
}

/*!
	@class			GlueUtils
	@abstract		Provides methods for help the framework and the user 
*/

/*!
	@method			getParameter
	@abstract		Get the specified URL 'GET' Parameter
	@property		parameter: the parameter's name
*/
GlueUtils.GETParameter = function(parameter) {
	var toReturn = null;
	var parsedUrl = Jaxer.request.parsedUrl;
	
	var fragment = parsedUrl.fragment;
	if(fragment != '') {
		// #anchor URLs first ex: #main=default.html&page=about.html
		var pList = fragment.split('&');
		for(var li = 0;li < pList.length;li ++) {
			var curParam = pList[li].split('=');
			if(curParam[0] == parameter) {
				toReturn = curParam[1];
			}
		}
	} else {
		// #?GET params second ex: ?main=default.html&page=about.html
		var queryParts = parsedUrl.queryParts;
		eval('toReturn = queryParts.'+parameter+';');
	}
	
	if(toReturn) toReturn = Jaxer.Util.String.escapeForJS(toReturn);
	
	return toReturn;
} 